// Thread.cpp: implementation of the Thread class.
//
//////////////////////////////////////////////////////////////////////

#include "Thread.h"
#include "Log.h"

//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////

Thread::Thread() : _tid(0),  _ret(1)
{
	memset(_name, sizeof(_name), 0);
	_tid = 0;
	_ret = 1;
}

Thread:: ~Thread()
{
}

int Thread::start()
{
	_working = true;
	//ul_writelog(UL_LOG_NOTICE, "start thread %s", get_name());
	NOTICE("start thread " << get_name());
	
    return pthread_create(&_tid, NULL, run_thread, this);
}

void* Thread::run_thread(void *para)
{
    Thread *t = static_cast<Thread *>(para);
    while (0 == t->_tid)
    {
        usleep(100000);
    }

    t->_ret = t->run();
	if (t->_ret != 0)
	{
        //ul_writelog(UL_LOG_FATAL, "thread %s abnormald end", t->get_name());
        FATAL("thread abnormald end: " <<  t->get_name());
	}
	else
	{
        //ul_writelog(UL_LOG_NOTICE, "thread %s normal end", t->get_name());
        NOTICE("thread normal end: "<<  t->get_name());
	}

    return 0;
}

int Thread::join()
{
    while (0 == _tid)
    {
        usleep(100000);
    }
    return pthread_join(_tid, NULL);
}

int Thread::detach()
{
    while (0 == _tid)
    {
        usleep(100000);
    }
    return pthread_detach(_tid);
}

pthread_t Thread::get_tid() const
{
    return _tid;
}

void Thread::set_name(const char *name)
{
    snprintf(_name, sizeof(_name), "%s", name);
}

void Thread::set_log()
{
}

const char* Thread::get_name() const
{
    return _name;
}

int Thread::get_ret() const
{
    return _ret;
}

void Thread::stop()
{
	_working = false;
	//ul_writelog(UL_LOG_NOTICE, "%s receive a stop signal", get_name());
	NOTICE("receive a stop signal: "<<get_name());
}

bool Thread::is_working()
{
	return _working;
}

bool Thread::init()
{
	return true;
}
